package Thread;

import java.io.*;

/*
    使用多线程完成文件的读写
 */
public class ReadAndWrite {
    public static void main(String[] args) throws FileNotFoundException {
        ReadWrite readWrite=new ReadWrite();
        Thread thread1=new Thread(readWrite);
        Thread thread2=new Thread(readWrite);
        thread1.start();
        thread2.start();
    }
}
class ReadWrite implements Runnable{
    File file1=new File("c:\\IOStream\\read.txt");
    File file2=new File("c:\\IOStream\\write.txt");
    FileInputStream fis=new FileInputStream(file1);
    FileOutputStream fos=new FileOutputStream(file2,true);
    byte buff[]=new byte[1024*8];  //设置缓冲区大小
    int index=-1;       //等于-1时表示程序刚开始或者文件已经读完了

    ReadWrite() throws FileNotFoundException {
    }

    @Override
    public void run() {
        while (true){
            synchronized (this){
                if(index==-1){
                    try {
                        index=fis.read(buff);   //读取文件
                        notify();
                        System.out.println(index);
                        if(index==-1){
                            break;      //文件已经读完
                        }
                        wait();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        fos.write(buff);
                        index=-1;
                        notify();
                        wait();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

}
